package com.knoya.chejian.pda.myclass;

import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;

import com.knoya.chejian.pda.Myapp;
import com.knoya.chejian.pda.util.FileUtils;
import com.knoya.chejian.pda.util.Myutil;
import com.knoya.chejian.pda.util.Sputil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Locale;

/**
 * Created by Administrator on 2016/12/28/028.
 * 作者：刘洋
 */
public class UnCeHandler implements Thread.UncaughtExceptionHandler {
    public static String activity="";
    public static String fragment="";
    public static String buzhou="";

    private Thread.UncaughtExceptionHandler mDefaultHandler;
    public static final String TAG = "CatchExcep";
    Myapp application;

    public UnCeHandler(Myapp application){
        //获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        this.application = application;
    }
    File folder;
    String time;
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if(!handleException(ex) && mDefaultHandler != null){
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        }else{
            try{
                Thread.sleep(3000);
            }catch (InterruptedException e){
                Log.e(TAG, "error : ", e);
            }

            mDefaultHandler.uncaughtException(thread, ex);
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(final Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
        new Thread(){
            @Override
            public void run() {
                Looper.prepare();
                Log.d("UnCeHandler","ex="+ex.toString());

                getError(ex.toString());
                Looper.loop();
            }
        }.start();
        return true;
    }
    private void getError(String error){
        JSONObject jo= new JSONObject();
        try {
            jo.put("手机系统语言",getSystemLanguage());
            jo.put("手机系统版本号 ",getSystemVersion());
            jo.put("手机型号",getSystemVersion());
            jo.put("手机厂商",getDeviceBrand());
            jo.put("时间",time);
            jo.put("app版本",getVersion());
            jo.put("uid", Sputil.sp("erp").getString("uid",""));
            jo.put("错误",error);
            jo.put("activity",activity);
            jo.put("fragment",fragment);
            jo.put("buzhou",buzhou);
        }catch (JSONException e){
            e.printStackTrace();
        }
        Log.d("UnCeHandler","error="+jo.toString());
        folder = new File(Environment
                .getExternalStorageDirectory().toString() + "/erp/error/");// 获得一个文件的路径
        time= Myutil.getjulidate(0);
        FileUtils.writeTxtToFile(jo.toString(), folder.toString() + "/","错误" + ".log");
        final SharedPreferences.Editor editor=Sputil.editor("erp");
        editor.putString("error",folder.toString() + "/"+"错误" + ".log");
        editor.putBoolean("errorok",false);
        editor.commit();
//        Httputil.updataError(Myapp.getContext(), Sputil.sp("erp").getString("uid", ""), Sputil.sp("erp").getString("error", ""), new OnUserDataInterface() {
//            @Override
//            public void onUserData(String data) {
//                editor.putBoolean("errorok",true);
//                editor.commit();
//                Log.d("UnCeHandler","=======================");
//            }
//
//            @Override
//            public void onNot(String throwable) {
//                Log.d("UnCeHandler","+++++++++++++++++++++");
//            }
//        });
    }
    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return  语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return  系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return  手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return  手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取当前版本的版本号
     *
     * @return 当前版本号，未成功则返回 版本号未知
     */
    private String getVersion() {
        try {
            PackageManager packageManager = Myapp.getContext().getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    Myapp.getContext().getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "版本号未知";
        }
    }
}